package com.google.ant.extensions.types;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.ant.extensions.SourceRepo;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class DependencyManager {
    private final SourceRepo sourceRepository;

    public DependencyManager() {
        this(new Project());
    }

    public DependencyManager(Project prj) {
        sourceRepository = new SourceRepo(prj);
    }

    private Collection<Module> getAllDependencies(final Module module) {
        Set<Module> results = new HashSet<Module>();

        for (Module m : module.getDependencies()) {
            if (!results.contains(m)) {
                results.addAll(getAllDependencies(m));                
            }
            results.add(m);
        }
        return results;
    }

    public Collection<Dependency> getDependencies(final Dependency dependency) {
        Set<Dependency> results = new HashSet<Dependency>();

        Module module = sourceRepository.get(dependency.getSignature());
        if (module != null) {
            Collection<Module> depModules = getAllDependencies(module);
            depModules.add(module);
            for (Module depModule : depModules) {
                results.addAll(getDependencies(depModule));
            }
        }
        return results;
    }

    public Collection<Dependency> getDependencies(final Module module) {
        Project moduleProject = new Project();
        if (new File(module.getBasedir()).exists()) {
            moduleProject.setBasedir(module.getBasedir());
            moduleProject.init();
            
            ProjectHelper.getProjectHelper().configureProject(moduleProject, 
                                                              new File(module.getBasedir(), 
                                                                       module.getBuildfile()));
        }

        Dependencies dep = (Dependencies) moduleProject.getReference(Dependency.PRJ_DEP_NAME);
        if (dep == null) {
            return new ArrayList<Dependency>();
        }

        return dep.getDependencies();
    }
}